package cn.cdeden.knowledge.controller.Individual;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.EnterpriseFilesTree;
import cn.cdeden.knowledge.domain.EnterprisePerm;
import cn.cdeden.knowledge.domain.vo.EnterpriseMemberVo;
import cn.cdeden.knowledge.domain.vo.EnterprisePermVo;
import cn.cdeden.knowledge.service.EnterpriseFilesTreeService;
import cn.cdeden.knowledge.service.EnterprisePermService;
import cn.cdeden.knowledge.domain.dto.EnterprisePermDto;
import cn.cdeden.system.api.model.LoginUser;
import cn.cdeden.system.api.model.RoleDTO;
import com.alibaba.fastjson.JSONArray;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
* @author Chen
* @date 2022-10-13
**/

@Controller
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/enterprisePerm")
public class EnterprisePermController {

    private final EnterprisePermService enterprisePermService;

    private final EnterpriseFilesTreeService enterpriseFilesTreeService;

/*
    */
/**
     *查询企业文档访问
     *
     * @param treeNodeId
     * @param type
     * @return
     *//*

    @GetMapping(value = "/query")
    @ResponseBody
    public R query(String treeNodeId, String type){
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        boolean rolePerm = ifUserIsEnterpriseAdmin();
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeService.getById(treeNodeId);
        if (userId == 1 || enterpriseFilesTree.getCreateId().equals(String.valueOf(userId))|| rolePerm) {
            return R.ok(enterprisePermService.queryAll(treeNodeId,type));
        }
        throw new BadRequestException("无查询权限！");
    }

    @PostMapping(value = "/update")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public BaseRespResult update(@RequestBody EnterprisePermVo enterprisePermVo){
        String resources = enterprisePermVo.getResources();
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<EnterprisePermDto> enterprisePermDtos = JSONArray.parseArray(resources, EnterprisePermDto.class);
        Long treeNodeId = enterprisePermVo.getTreeNodeId();
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeService.getById(treeNodeId);
        boolean rolePerm = ifUserIsEnterpriseAdmin();
        //判断是否为管理员或者用户文档管理员
*/
/*
        if (user.getId() == 1 || enterpriseFilesTree.getCreateId().equals(String.valueOf(user.getId())) || rolePerm) {
            enterprisePermService.removeByFileId(treeNodeId);
            for (int i = 0; i < enterprisePermDtos.size(); i++) {
                EnterprisePermDto enterprisePermDto = enterprisePermDtos.get(i);
                enterprisePermDto.listChangeObject();
                enterprisePermDto.setTreeNodeId(treeNodeId);
                enterprisePermService.insert(enterprisePermDtos.get(i));
            }
            return BaseRespResult.successResult("200","修改成功！");
        }
*//*

        //判断是否为管理员或者用户文档管理员
        if (user.getId() == 1 || rolePerm) {
            enterprisePermService.removeByFileId(treeNodeId);
            for (int i = 0; i < enterprisePermDtos.size(); i++) {
                //新增权限信息
                EnterprisePermDto enterprisePermDto = enterprisePermDtos.get(i);
                enterprisePermDto.listChangeObject();
                enterprisePermDto.setTreeNodeId(treeNodeId);
                enterprisePermService.insert(enterprisePermDtos.get(i));
            }
            return BaseRespResult.successResult("200", "修改成功！");
        }else{
            throw new BadRequestException("无修改权限！");
        }

    }
*/

    /*
判断当前角色是否是企业管理员（企业管理员id为5）
 */
    private boolean ifUserIsEnterpriseAdmin(){
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<RoleDTO> roles = loginUser.getRoles();
        for (RoleDTO role : roles) {
            if (role.getRoleName().equals("企业管理员"))
                return true;
        }
        return false;
    }




    /*************************修改版本，重写接口*************************/

    /**
     * 查询用户下角色绑定
     * @param treeNodeId    树节点
     * @param nickname      昵称
     * @param params        权限
     * @param types          维度
     * @param pageable      分页
     * @return
     */
    @GetMapping(value = "/selectRoler")
    public R selectRoler(@RequestParam(required = true) Long treeNodeId,
                                      @RequestParam(required = false) String nickname,
                                      @RequestParam(required = false) String params,
                                      @RequestParam(required = false) String types,
                                      Pageable pageable){
        TableDataInfo<EnterpriseMemberVo> info = enterprisePermService.selectPermissionsByTreeNodeIdNew(treeNodeId, types ,params ,nickname, pageable);
        return R.ok(info);
    }




    /**
     * 查询用户下角色绑定
     * @param treeNodeId    树节点
     * @param nickname      昵称
     * @param params        权限
     * @param types          维度
     * @return
     */
    @GetMapping(value = "/api/job/queryUnlimited")
    public R selectRolerList(@RequestParam(required = true) Long treeNodeId,
                                          @RequestParam(required = false) String nickname,
                                          @RequestParam(required = false) String params,
                                          @RequestParam(required = false) String types
                                      ){
        List<EnterpriseMemberVo> list = enterprisePermService.selectPermissionsByTreeNodeIdNew(treeNodeId, types ,params ,nickname);
        return R.ok(list);
    }
    /**
     * 更新用户角色绑定
     * @param permResource
     * @return
     */
    @PostMapping(value = "/updateRoler")
    public R updateRoler(@RequestBody EnterprisePermDto permResource){
        enterprisePermService.updatePermissionsByTreeNodeId(permResource.getIds(),permResource.getParams(),permResource.getTreeNodeId());
        return R.ok();
    }

/*
    */
/**
     * 新增用户角色绑定
     * @param permResource
     * @return
     */

    @PostMapping(value = "/inertRoler")
    public R insertRoler(@RequestBody EnterprisePermDto permResource){
        enterprisePermService.insertPermissionsByTreeNodeIds(permResource.getEnterprisePermDtos(), permResource.getTreeNodeId());
        return R.ok();
    }

/**
     * 删除用户角色绑定
     * @param permResource
     * @return
     */

    @PostMapping(value = "/deleteRoler")
    public R deleteRoler(@RequestBody EnterprisePermDto permResource){
        enterprisePermService.deletePermissionsByTreeNodeId(permResource.getIds(), permResource.getTreeNodeId());
        return R.ok();
    }

/**
     * 同步所有下级权限
     */

    @PostMapping(value = "/synchronizedChildrenAllPerm")
    public R synchronizedChildrenAllPerm(@RequestBody EnterprisePerm enterprisePerm) throws InterruptedException {
        enterprisePermService.synchronizedChildrenAllPerm(enterprisePerm.getTreeNodeId());
        return R.ok();
    }

    /**
     * 移交权限
     */

    @PostMapping(value = "/transferPerm")
    public R transferPerm(@RequestBody Map<String,Long> arg) {
        enterprisePermService.transferPerm(arg.get("transferId"), arg.get("targetId"));
        return R.ok();
    }

}
